import React from 'react';
import { observer, inject } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import Sortable from 'react-sortablejs';
import { Accordion, Icon, Result, ActivityIndicator, Carousel, Badge, Tools } from 'weaver-mobile';

import introJs from 'intro.js';
// 样式自动加载不生效
import 'intro.js/minified/introjs.min.css';
import 'intro.js/minified/introjs-rtl.min.css';
import '../style/intro/index.less';

const getLabel = Tools.getLabel;
const { getFrameParams } = Tools;

@inject('homePageTestStore')
@withRouter
@observer
export default class EntrancePage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      timer: null,
    }
  }

  componentDidMount() {
    const { homePageTestStore } = this.props;
    const { getCorner, initEntrancePage, setState, isEdit, showGroup, menuConfig, hasAdd, getMenuConfig, getCount } = homePageTestStore;

    // if (window.em && window.em.checkJsApi('registerBroadcast')) {
    //   window.em.registerBroadcast({
    //     name: "_closeWfFormCallBack",
    //     action: () => {
    //       getCorner();
    //     }
    //   });
    // } else {
    //   window.__closeFormCallBack = getCorner;
    // }

    if (window.em) {
      window.em.ready(() => {
        window.em.appEventListener({
          'name': 'KPageVisibleNotificationName', 'action': (argument) => {
            //name 关心的事件，1. KBadgeChangedNotificationName 未读数角标变化
            //action 事件回调
            if (typeof (argument) == 'string') {
              try {
                argument = JSON.parse(argument)
              } catch (error) {

              }
            }
            if (argument.visible) {
              setTimeout(() => {
                getCorner();
              }, window.reloadCornerDelay || 10)
            }
          }, 'success': function (res) {
            //注册监听成功
          }
        })
      });
    } else {
      console && console.log('em未加载')
    }

    if (showGroup) {
      let length = [];
      for (let index = 0; index < menuConfig.length; index++) {
        length.push(index + '');
      }
      setState({ activeKey: length })
    }

    if (hasAdd) {
      getMenuConfig().then(() => {
        getCorner()
        this.touchInit();
        if (!isEdit || initEntrancePage) {
          this.getEditNav();
        } else {
          this.getSaveNav()
        }
      })
    } else {
      getCorner().then(() => {
        this.touchInit();
        if (!isEdit || initEntrancePage) {
          this.getEditNav();
        } else {
          this.getSaveNav()
        }
      })
    }

    // 轮询部分角标
    this.interval = setInterval(() => {
      getCorner();
    }, window.refreshEntranceInterval || 60000)
  }

  componentWillUnmount() {
    const { homePageTestStore } = this.props;
    const { setState } = homePageTestStore;

    setState({ hasAdd: false })

    document.getElementsByClassName('introjs-overlay').length && document.body.removeChild(document.getElementsByClassName('introjs-overlay')[0])
    document.getElementsByClassName('introjs-helperLayer').length && document.body.removeChild(document.getElementsByClassName('introjs-helperLayer')[0])
    document.getElementsByClassName('introjs-tooltipReferenceLayer').length && document.body.removeChild(document.getElementsByClassName('introjs-tooltipReferenceLayer')[0])

    if (this.interval) {
      clearInterval(this.interval);
    }
  }

  getEditNav = () => {
    const { homePageTestStore } = this.props;
    const { setState } = homePageTestStore;
    setState({ initEntrancePage: false })

    let that = this;

    if (window.em && window.em.checkJsApi("configNavigation")) {
      window.em.ready(function () {
        window.em.configNavigation({
          'success': function (argument) { },
          'fail': function (argument) { },
          'cancel': function (argument) { },
          'complete': function (argument) { },
          'left': {
            'title': getLabel('503074', '工作台'),
          },  //左侧按钮的名字 回调事件，回调的参数，单个事件
          'right': {
            'name': getLabel('501169', '编辑'),
            'action': function () {
              that.onEdit()
            }
          },  //右侧按钮的 名字 多个，回调事件列表 回调参数列表
          'title': '',
          'showCloseButton': false  // 是否显示关闭按钮，显示之后 一键关闭，不传，按默认行为处理
        })
      });
    }
  }

  getSaveNav = () => {
    let that = this;

    if (window.em && window.em.checkJsApi("configNavigation")) {
      window.em.ready(function () {
        window.em.configNavigation({
          'success': function (argument) { },
          'fail': function (argument) { },
          'cancel': function (argument) { },
          'complete': function (argument) { },
          'left': {
            'title': getLabel('503074', '工作台'),
          },  //左侧按钮的名字 回调事件，回调的参数，单个事件
          'right': {
            'name': getLabel('30986', '保存'),
            'action': function () {
              that.onSave()
            }
          },  //右侧按钮的 名字 多个，回调事件列表 回调参数列表
          'title': '',
          'showCloseButton': false  // 是否显示关闭按钮，显示之后 一键关闭，不传，按默认行为处理
        })
      });
    }
  }

  touchInit = () => {
    const ua = window.navigator.userAgent;
    const inMobile = (/.*E-Mobile7.*/.test(ua)
      || /.*E-Mobile\/7.*/.test(ua)
    )
    // 仅在em下
    if (!inMobile) {
      return;
    }

    let startTime = '';
    let endTime = '';
    let timer = '';
    const menuItem = document.querySelector('.wm-home-page')

    menuItem && menuItem.addEventListener('touchstart', (e) => {
      startTime = +new Date();
      if (e.target.classList.contains('entrance-item-icon') || e.target.classList.contains('entrance-item-title')) {
        timer = setTimeout(() => {
          this.onEdit()
        }, 1200)
      }
    })

    menuItem && menuItem.addEventListener('touchend', (e) => {
      endTime = +new Date();
      if (e.target.classList.contains('entrance-item-icon') || e.target.classList.contains('entrance-item-title')) {
        if (endTime - startTime < 1200) {
          clearTimeout(timer)
          // if (isEdit){
          //   const hiddenItemId = e.path[2].attributes[1].nodeValue;
          //   this.hiddenItem(hiddenItemId);
          // }
        }
      }
    })
  }

  toMore = () => {
    const query = this.props.history.location.search
    this.props.history.push(`/hiden-page${query}`)
  }

  onChange = (key) => {
    this.props.onChange && this.props.onChange(key)
  }

  onSave = () => {
    const { homePageTestStore } = this.props;
    const { saveMenuConfig, setState, menuConfig } = homePageTestStore;

    let length = [];
    for (let index = 0; index < menuConfig.length; index++) {
      length.push(index + '');
    }
    setState({
      activeKey: length,
      isMenuInited: false,
    })

    this.getEditNav()

    saveMenuConfig()

    introJs().exit();

    if (document.getElementsByClassName("wm-home-footer").length > 0) {
      const domLen = document.getElementsByClassName("wm-home-footer").length;
      for (let i = 0; i < domLen; i++) {
        document.getElementsByClassName("wm-home-footer")[i].style.display = 'none';
      }
    }
  }

  onEdit = () => {
    const { homePageTestStore } = this.props;
    const { setState, showGroup, getMenuConfig, menuConfig, getCorner, isEdit, isInit, hasIntro } = homePageTestStore;

    if (showGroup) {
      let length = [];
      for (let index = 0; index < menuConfig.length; index++) {
        length.push(index + '');
      }
      setState({ activeKey: length })
    }

    if (isEdit) {
      return false
    }

    this.getSaveNav()
    !showGroup && setState({ isMenuInited: false });
    setState({ isEdit: true });
    if (!showGroup) {
      getMenuConfig().then(() => {
        getCorner();
        if (isInit && !hasIntro) {
          setState({ hasIntro: true })
          let introOptions = {
            overlayOpacity: 0.6,
            showBullets: false,
            nextLabel: getLabel("1402", "下一步"),
            prevLabel: getLabel("1876 ", "上一步"),
            skipLabel: getLabel("382972", "跳过"),
            doneLabel: getLabel("383773", "知道了"),
            showStepNumbers: false,
            tooltipClass: "wea-intro-tooltip",
            exitOnOverlayClick: false,
            hideNext: true,
            hidePrev: true,
          }
          introJs().setOptions(introOptions).start()
          introJs().oncomplete(function () {
            if (document.getElementsByClassName("wm-home-more").length > 0) {
              document.getElementsByClassName("wm-home-more")[0].style.display = 'none';
            }
          });

          let moreNode = document.getElementsByClassName('wm-home-more').length && document.getElementsByClassName("wm-home-more")[0];
          let introHelpNode = document.getElementsByClassName('introjs-helperLayer');
          introHelpNode && introHelpNode.length && introHelpNode[0] && introHelpNode[0].appendChild(moreNode);
        }
      })
    } else {
      if (isInit && !hasIntro) {
        setState({ hasIntro: true })
        let introOptions = {
          overlayOpacity: 0.6,
          showBullets: false,
          nextLabel: getLabel("1402", "下一步"),
          prevLabel: getLabel("1876 ", "上一步"),
          skipLabel: getLabel("382972", "跳过"),
          doneLabel: getLabel("383773", "知道了"),
          showStepNumbers: false,
          tooltipClass: "wea-intro-tooltip",
          exitOnOverlayClick: false,
          hideNext: true,
          hidePrev: true,
        }
        introJs().setOptions(introOptions).start()
        introJs().oncomplete(function () {
          if (document.getElementsByClassName("wm-home-more").length > 0) {
            document.getElementsByClassName("wm-home-more")[0].style.display = 'none';
          }
        });

        let moreNode = document.getElementsByClassName('wm-home-more').length && document.getElementsByClassName("wm-home-more")[0];
        let introHelpNode = document.getElementsByClassName('introjs-helperLayer');
        introHelpNode && introHelpNode.length && introHelpNode[0] && introHelpNode[0].appendChild(moreNode);
      }
    }
  }

  onReset = () => {
    const { homePageTestStore } = this.props;
    const { resetMenuConfig } = homePageTestStore;

    resetMenuConfig()
  }

  renderMenuItem(group) {
    const { homePageTestStore } = this.props;
    const { showCountListInfo, isEdit } = homePageTestStore;

    let menuItemEles = [];

    for (let itemindex = 0; itemindex < group.groupItem.length; itemindex++) {
      let item = group.groupItem[itemindex];
      item.id && !item.hiden && menuItemEles.push((
        <RenderAppItem
          key={item.id}
          item={item}
          showCountListInfo={showCountListInfo}
          isEdit={isEdit}
        />
      ))
    }

    return menuItemEles;
  }

  renderMenu(menuConfig, needGroup = true) {
    const { homePageTestStore } = this.props;
    const { isEdit, setState, doSort, showCountListInfo } = homePageTestStore;

    let menuEles = [];
    let renderItemsData = [];

    const SortableList = ({ items, onChange, index }) => {
      return (
        <Sortable
          tag="ul"
          onChange={(order, sortable, evt) => {
            for (let i = 0, lenI = order.length; i < lenI; i++) {
              if (needGroup || isEdit) {
                for (let j = 0, lenJ = menuConfig[index].groupItem.length; j < lenJ; j++) {
                  if (menuConfig[index].groupItem[j].id === order[i]) {
                    menuConfig[index].groupItem[j].module_show_order = i;
                    setState({ hasCustom: true })
                  }
                }
                doSort(menuConfig[index].groupItem, 'module_show_order');
              } else {
                const lenJ = menuConfig.length;
                for (let j = 0; j < lenJ; j++) {
                  if (menuConfig[j].id === order[i]) {
                    menuConfig[j].module_show_order = i;
                    setState({ hasCustom: true })
                  }
                }
                doSort(menuConfig, 'module_show_order');
              }
            }
            onChange(menuConfig, index);
          }}
        >
          {items}
        </Sortable>
      );
    }

    for (let index = 0; index < menuConfig.length; index++) {
      if (needGroup || isEdit) {
        let group = menuConfig[index];
        let items = {}

        if (group.groupItem && group.groupItem.length > 0) {
          items = this.renderMenuItem(group)
          if (items.length > 0) {
            menuEles.push(
              <Accordion.Panel key={index}
                header={group.groupTitle}
                className="entrance-content"
                style={index === menuConfig.length - 1 ? { borderBottom: 'none' } : null}>
                {!isEdit ? items : (
                  <SortableList
                    key={index}
                    items={items}
                    onChange={(items, index) => {
                      setState({ menuConfig: items });
                    }}
                    index={index}
                  />
                )}
              </Accordion.Panel>
            )
          }
        }
      } else {
        renderItemsData.push(
          <RenderAppItem
            key={menuConfig[index].id || menuConfig[index].title}
            item={menuConfig[index]}
            showCountListInfo={showCountListInfo}
            isEdit={isEdit}
          />
        )
      }
    }

    if (renderItemsData.length > 0) {
      menuEles = isEdit ? <SortableList
        key={renderItemsData[0].id}
        items={renderItemsData}
        onChange={(items) => {
          setState({ menuConfig: items });
        }}
      /> : renderItemsData
    }

    return menuEles;
  }

  render() {
    const { showGroup, activeKey, disableMenu, isMenuInited, homePageTestStore } = this.props;
    const { bannerFlag, bannerImg, bannerHeight, isEdit } = homePageTestStore;
    const menuConfig = this.props.menuConfig || window.menuPageConfig || [];
    let hasCarousel = false;
    let imgs = [];
    if (bannerImg.length > 0) {
      bannerImg.map(item => {
        imgs.push(item.imgSrc);
      })
    }
    // let imgs = bannerImg.length > 0 ? bannerImg.split(' ') : [];
    if (bannerFlag === '1' && imgs.length > 0) {
      hasCarousel = true;
    }
    const carousel = imgs.length === 1 ? (<a
      key={imgs[0]}
      style={{ display: 'inline-block', width: '100%', height: parseInt(bannerHeight) || '180px' }}
    >
      <img
        src={imgs[0]}
        alt=""
        style={{ width: '100%', verticalAlign: 'top', height: '100%' }}
        onLoad={() => {
          // fire window resize event to change height
          window.dispatchEvent(new Event('resize'));
        }}
      />
    </a>) : (
        <Carousel
          autoplay={true}
          infinite
        >
          {
            imgs.map(val => (
              <a
                key={val}
                // href={val}
                style={{ display: 'inline-block', width: '100%', height: parseInt(bannerHeight) || '180px' }}
              >
                <img
                  src={val}
                  alt=""
                  style={{ width: '100%', verticalAlign: 'top', height: '100%' }}
                  onLoad={() => {
                    // fire window resize event to change height
                    window.dispatchEvent(new Event('resize'));
                  }}
                />
              </a>
            ))}
        </Carousel>
      )

    if (disableMenu === 0) {
      return (<div className="wm-home-page">
        {hasCarousel && carousel}
        <div className='img-container'>
          <img src="../../../../spa/coms/images/menu_nodata.png"></img>
          <span>页面维护中，暂停使用</span>
        </div>
      </div>)
    }

    if (isMenuInited) {
      if (showGroup === true || (!showGroup && isEdit)) {
        let menu = this.renderMenu(menuConfig);

        return (
          <div id="entrance-page">
            {/*<div onClick={this.onEdit}>编辑</div>*/}
            {/*<div onClick={this.onSave}>保存</div>*/}
            {hasCarousel && carousel}
            {
              (menu.length > 0 || isEdit) ? (
                <div>
                  <Accordion defaultActiveKey={activeKey}
                    className="wm-home-page"
                    onChange={this.onChange}>
                    {menu}
                    {
                      isEdit && (
                        <div className="wm-footer-more"
                          onClick={this.toMore}>{getLabel('17499', '更多')}
                          <Icon color="lightslategray"
                            type={'right'} />
                        </div>
                      )
                    }
                  </Accordion>
                  <div className="wm-home-footer" style={{ display: 'none' }}>
                    <div id='more'
                      data-step="1"
                      data-intro={getLabel('513074', '隐藏的应用及其重新显示操作都在这里')}
                      data-position='bottom'
                      data-scrollto='tooltip'>
                      <div className="wm-home-more"
                        onClick={this.toMore}>{getLabel('17499', '更多')}
                        <Icon color="lightslategray"
                          type={'right'} />
                      </div>
                    </div>
                    <div className="wm-home-reset"
                      onClick={this.onReset}>{getLabel('512887', '恢复默认排序')}</div>
                  </div>
                </div>
              ) : ((!menu.length && !isEdit) && <Result className="wm-home-result"
                img={<Icon type={'no-data'} size='lg' />}
                message={getLabel('83553', '暂无数据')}
              />)
            }

            {isEdit && (
              <div className="wm-home-footer">
                <div className="wm-home-reset"
                  onClick={this.onReset}>{getLabel('512887', '恢复默认排序')}</div>
              </div>
            )}
          </div>
        )
      } else {
        let menu = this.renderMenu(menuConfig, false);

        if (menu.length === 0) {
          return (<div className="wm-home-page">
            {hasCarousel && carousel}
            {!isEdit && <Result className="wm-home-result"
              img={<Icon type={'no-data'} size='lg' />}
              message={getLabel('83553', '暂无数据')}
            />
            }
            {isEdit && (
              <div className="wm-footer-more"
                onClick={this.toMore}>{getLabel('17499', '更多')}
                <Icon color="lightslategray"
                  type={'right'} />
              </div>
            )}
          </div>)
        }

        return (
          <div id="entrance-page">
            <div className="wm-home-page">
              {hasCarousel && carousel}
              {menu}
              {isEdit && (
                <div className="wm-footer-more"
                  onClick={this.toMore}>{getLabel('17499', '更多')}
                  <Icon color="lightslategray"
                    type={'right'} />
                </div>
              )}
            </div>
            <div className="wm-home-footer" style={{ display: 'none' }}>
              <div id='more'
                data-step="1"
                data-intro={getLabel('513074', '隐藏的应用及其重新显示操作都在这里')}
                data-position='bottom'
                data-scrollTo='tooltip'>
                <div className="wRenderAppItemm-home-more"
                  onClick={this.toMore}>{getLabel('17499', '更多')}
                  <Icon color="lightslategray"
                    type={'right'} />
                </div>
              </div>
              <div className="wm-home-reset"
                onClick={this.onReset}>{getLabel('512887', '恢复默认排序')}</div>
            </div>
            {isEdit && (
              <div className="wm-home-footer">
                <div className="wm-home-reset"
                  onClick={this.onReset}>{getLabel('512887', '恢复默认排序')}</div>
              </div>
            )}
          </div>
        )
      }
    } else {
      return (
        <div style={{ height: '100%' }}>
          <div style={{ height: '240px' }}></div>
          <ActivityIndicator size='large' animating text="loading" />
        </div>
      )
    }
  }
}

@inject('homePageTestStore')
@withRouter
@observer
class RenderAppItem extends React.Component {
  constructor(props) {
    super(props);
  }

  hiddenItem = (hiddenItemId) => {
    const { homePageTestStore } = this.props;
    const { menuConfig, setState, showGroup, isEdit, saveMenuConfig } = homePageTestStore;
    const updateTime = new Date().toLocaleDateString().replace(/\//g, "-") + " " + new Date().toTimeString().substr(0, 8) + ":" + new Date().getMilliseconds();

    // 删除隐藏单个app应用
    if (showGroup || isEdit) {
      menuConfig.forEach((menuItem, menuIndex) => {
        if (menuItem.groupItem && menuItem.groupItem.length > 0) {
          menuItem.groupItem.forEach((appItem, appIndex) => {
            if (appItem.id === hiddenItemId) {
              menuConfig[menuIndex].groupItem[appIndex].updateTime = updateTime
              menuConfig[menuIndex].groupItem.splice(appIndex, 1);
              setState({ hasCustom: true })
              if (!menuConfig[menuIndex].groupItem.length) {
                menuConfig.splice(menuIndex, 1)
              }
            }
          })
        }
      })
    } else {
      menuConfig.forEach((menuItem, menuIndex) => {
        if (menuItem && menuItem.id === hiddenItemId) {
          menuConfig[menuIndex].updateTime = updateTime
          menuConfig.splice(menuIndex, 1);
          setState({ hasCustom: true })
        }
      })
    }

    saveMenuConfig(hiddenItemId)
  }

  onItemClick(item) {
    const { homePageTestStore } = this.props;
    const { isEdit } = homePageTestStore;
    if (isEdit) {
      return false
    }

    if (/.*hasEmCode.*/.test(window.location.href) && !item.inteSysid && item.inteSwitch !== '1') {
      // if (/.*\?.*/.test(item.itemUrl)) {
      //   item.itemUrl += '&hasEmCode=1'
      // } else {
      //   item.itemUrl += '?hasEmCode=1'
      // }
      var split = '';
      var hasEmCodeParam = '';
      if (/.*\?.*/.test(item.itemUrl)) {
        split = '&'
        if (/.*\?.*#\/(?!.*\?).*/.test(item.itemUrl)) {
          split = '?'
        }
      } else {
        split = '?'
      }
      hasEmCodeParam = 'hasEmCode=1'
      item.itemUrl += (split + hasEmCodeParam)
    }
    if (item.inteSwitch === '1' || item.inteSysid) {
      // 跳转用户录入页面
      window.openLink.openInteApp(item);
      // setState({ currentItem: item });
      // getOutterPCAndAppUrl(item, this.props.history);
    } else if (item.openApp === '1') {
      // 第三方app
      if (window.em) {
        let params = {};
        let iosScheme = item.iosScheme;
        let androidScheme = item.androidScheme;
        if (item.iosScheme.indexOf('?') !== -1) {
          let urlParams = getFrameParams(item.iosScheme);
          let keys = Object.keys(urlParams);
          let values = Object.values(urlParams);
          keys.map((item, index) => {
            params[item] = values[index];
          })
          iosScheme = iosScheme.split('?')[0];
        }
        if (item.androidScheme.indexOf('?') !== -1) {
          androidScheme = androidScheme.split('?')[0];
        }
        window.em.checkJsApi("openApp") && window.em.openApp({
          iOSscheme: iosScheme,
          iOSurl: item.iosUrl,
          androidscheme: androidScheme,
          androidurl: item.androidUrl,
          params: params,
          error: function (error) {
            alert(JSON.stringify(error));
          }
        })
        !window.em.checkJsApi("openApp") && window.openLink(item.itemUrl);
      } else {
        window.openLink(item.itemUrl);
      }
    } else if (window.em && window.localStorage.emobile_ec_id) {
      // 内部应用
      if (window.em.checkJsApi("openLink")) {
        // 带http的地址暂时认定为不需要em信息的第三方应用地址
        if (/http/.test(item.itemUrl)) {
          window.em.openLink({
            url: item.itemUrl,
            openType: item.openType,
            error: function (error) {
              alert(JSON.stringify(error));
            }
          })
        } else {
          // if (item.itemUrl.indexOf('localworkflow') !== -1) {
          //   const version = Math.ceil(Math.random() * 1000) + Math.ceil(Math.random() * 1000)
          //   window.em.getEmAuthCode({
          //     sysId: window.localStorage.emobile_ec_id, // 集成系统ID
          //     success: function (emres) {
          //       // 如：{"em_auth_code":"abc123","errMsg":"getEmAuthCode:ok"}
          //       if (emres.em_auth_code) {
          //         window.em.invoke('openApplication', {
          //           'appzipfile': '/spaLocal/workflow.zip',
          //           'baseurl': window.location.origin,
          //           'version': version,//字符串类型的整数值
          //           'minversion': 10000, //字符串类型的整数值
          //           'indexpage': 'workflow/static4mobile/app/dist/index.html#/center/doing?debugwithvconsole=true',//zip解压后的indexpage，第一层文件夹为解压后的文件夹名称
          //           'query': '&em_auth_code=' + emres.em_auth_code,
          //           'success': function (argument) {
          //           },
          //           'error': function (error) {
          //             alert(JSON.stringify(error));
          //           }
          //         })
          //       }
          //     },
          //     error: function (error) {
          //       alert('重新获取em_auth_code失败: ' + JSON.stringify(error));
          //     }
          //   });
          // } else if (item.itemUrl.indexOf('locallogin') !== -1) {
          //   const version = Math.ceil(Math.random() * 1000) + Math.ceil(Math.random() * 1000)
          //   window.em.invoke('openApplication', {
          //     'appzipfile': '/spaLocal/coms.zip',
          //     'baseurl': window.location.origin,
          //     'version': version,//字符串类型的整数值
          //     'minversion': 10000, //字符串类型的整数值
          //     'indexpage': 'coms/sso/app/dist/index.html#/Login?debugwithvconsole=true',//zip解压后的indexpage，第一层文件夹为解压后的文件夹名称
          //     'success': function (argument) {
          //     },
          //     'error': function (error) {
          //       alert(JSON.stringify(error));
          //     }
          //   })
          // }
          //  else if (item.itemUrl.indexOf('cowork') !== -1) {
          //   const version = Math.ceil(Math.random() * 1000) + Math.ceil(Math.random() * 1000)
          //   window.em.getEmAuthCode({
          //     sysId: window.localStorage.emobile_ec_id, // 集成系统ID
          //     success: function (emres) {
          //       // 如：{"em_auth_code":"abc123","errMsg":"getEmAuthCode:ok"}
          //       if (emres.em_auth_code) {
          //         window.em.invoke('openApplication', {
          //           'appzipfile': '/spaLocal/cowork.zip',
          //           'baseurl': window.location.origin,
          //           'version': version,//字符串类型的整数值
          //           'minversion': 10000, //字符串类型的整数值
          //           'indexpage': 'cowork/static4mobile/app/dist/index.html#/communication?debugwithvconsole=true',//zip解压后的indexpage，第一层文件夹为解压后的文件夹名称
          //           'query': '&em_auth_code=' + emres.em_auth_code,
          //           'success': function (argument) {
          //           },
          //           'error': function (error) {
          //             alert(JSON.stringify(error));
          //           }
          //         })
          //       } else {
          //         alert('重新获取em_auth_code失败');
          //       }
          //     },
          //     error: function (error) {
          //       alert('重新获取em_auth_code失败: ' + JSON.stringify(error));
          //     }
          //   });

          //   // window.em.getEmAuthCode({
          //   //   sysId: 'bd3bc26d742641edb159bbc5b623da59',
          //   //   // corpId: 'ema65d8dd68b3f11e9a652005056bc3615', // 企业corpid
          //   //   success: function (res) {
          //   //     alert(res.em_auth_code)

          //   //     // 如：{"em_auth_code":"abc123","errMsg":"getEmAuthCode:ok"}
          //   //   }
          //   // });

          // }
          // else {
          window.em.openLink({
            url: item.itemUrl,
            openType: item.openType,
            sysId: window.localStorage.emobile_ec_id,
            error: function (error) {
              alert(JSON.stringify(error));
            }
          })
          // }
        }
      }
      !window.em.checkJsApi("openLink") && window.openLink(item.itemUrl);
    } else {
      window.openLink(item.itemUrl);
    }
  }
  render() {
    const { item, showCountListInfo, isEdit } = this.props;
    return (
      item.id ? (
        <li className="entrance-item"
          data-id={item.id}
          key={item.id}>
          {/* {item.itemType !== '1' && <img className="entrance-item-icon" src={item.itemCusIcon || item.itemIcon} onClick={() => this.onItemClick(item)} ></img>} */}
          {item.showCount &&
            <Badge text={showCountListInfo[item.appid] && item.showCountType == '1' ? showCountListInfo[item.appid].unread : ''}
              dot={item.showCountType == '2' && showCountListInfo[item.appid] && showCountListInfo[item.appid].unread && parseInt(showCountListInfo[item.appid].unread) > 0}
              className={isEdit ? "entrance-item-animate" : null}
            >
              {isEdit && <a className="entrance-item-hidden-icon"
                style={{ cursor: 'pointer' }}
                onClick={() => this.hiddenItem(item.id)}>
                <Icon type="delete-o" color="red" />
              </a>}
              <img className="entrance-item-icon"
                src={item.itemCusIcon || item.itemIcon}
                onClick={() => this.onItemClick(item)} />
            </Badge>}
          {!item.showCount &&
            <div className={isEdit ? "entrance-item-animate" : null}>
              {isEdit && <a className="entrance-item-hidden-icon"
                style={{ cursor: 'pointer' }}
                onClick={() => this.hiddenItem(item.id)}>
                <Icon type="delete-o" color="red" />
              </a>}
              <img className="entrance-item-icon"
                src={item.itemCusIcon || item.itemIcon}
                onClick={() => this.onItemClick(item)} />
            </div>}
          <div className="entrance-item-title">{item.itemTitle}</div>
        </li>
      ) : null
    )
  }
}
